/**
 * @param {number[][]} grid
 * @return {number}
 */
var minPathSum = function (grid) {
  const m = grid[0].length
  const n = grid.length
  const f = new Array(n).fill(0).map(() => new Array(m).fill(0))
  f[0][0] = grid[0][0]
  for (let i = 1; i < n; i++) {
    f[i][0] = f[i - 1][0] + grid[i][0]
  }
  for (let i = 1; i < m; i++) {
    f[0][i] = f[0][i - 1] + grid[0][i]
  }
  console.log(f)
  for (let i = 1; i < n; i++) {
    for (let j = 1; j < m; j++) {
      f[i][j] = Math.min(f[i - 1][j] + grid[i][j], f[i][j - 1] + grid[i][j])
    }
  }
  return f[n - 1][m - 1]
}
console.log(
  minPathSum([
    [1, 3, 1],
    [1, 5, 1],
    [4, 2, 1]
  ])
)
